const axios = require('axios');

const BASE_URL = 'http://localhost:4000/api';
let authToken = '';

// 测试配置
const testConfig = {
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
};

// 登录获取token
async function login() {
  try {
    console.log('🔐 正在登录...');
    const response = await axios.post(`${BASE_URL}/auth/login`, {
      username: 'admin',
      password: 'admin123'
    }, testConfig);
    
    if (response.data.code === 200) {
      authToken = response.data.data.accessToken;
      console.log('✅ 登录成功，获取到token');
      return true;
    } else {
      console.log('❌ 登录失败:', response.data.message);
      return false;
    }
  } catch (error) {
    console.log('❌ 登录请求失败:', error.message);
    return false;
  }
}

// 测试获取所有设置
async function testGetAllSettings() {
  try {
    console.log('\n📋 测试获取所有设置...');
    const response = await axios.get(`${BASE_URL}/settings`, {
      ...testConfig,
      headers: {
        ...testConfig.headers,
        'Authorization': `Bearer ${authToken}`
      }
    });
    
    if (response.data.code === 200) {
      console.log('✅ 获取所有设置成功');
      console.log('📊 设置分类数量:', Object.keys(response.data.data.settings).length);
      
      // 显示各分类的基本信息
      Object.entries(response.data.data.settings).forEach(([category, settings]) => {
        console.log(`  - ${category}: ${Object.keys(settings).length} 项配置`);
      });
      
      return response.data.data.settings;
    } else {
      console.log('❌ 获取设置失败:', response.data.message);
      return null;
    }
  } catch (error) {
    console.log('❌ 获取设置请求失败:', error.message);
    if (error.response) {
      console.log('  状态码:', error.response.status);
      console.log('  错误信息:', error.response.data);
    }
    return null;
  }
}

// 测试获取特定分类设置
async function testGetCategorySettings(category) {
  try {
    console.log(`\n📋 测试获取${category}设置...`);
    const response = await axios.get(`${BASE_URL}/settings/${category}`, {
      ...testConfig,
      headers: {
        ...testConfig.headers,
        'Authorization': `Bearer ${authToken}`
      }
    });
    
    if (response.data.code === 200) {
      console.log(`✅ 获取${category}设置成功`);
      console.log(`📊 配置项数量: ${Object.keys(response.data.data.settings).length}`);
      return response.data.data.settings;
    } else {
      console.log(`❌ 获取${category}设置失败:`, response.data.message);
      return null;
    }
  } catch (error) {
    console.log(`❌ 获取${category}设置请求失败:`, error.message);
    if (error.response) {
      console.log('  状态码:', error.response.status);
      console.log('  错误信息:', error.response.data);
    }
    return null;
  }
}

// 测试更新设置
async function testUpdateSettings() {
  try {
    console.log('\n📝 测试更新设置...');
    
    const updateData = {
      general: {
        siteName: '知识库管理系统 - 测试版',
        postsPerPage: 25
      },
      security: {
        passwordMinLength: 8,
        sessionTimeout: 45
      },
      notifications: {
        events: {
          newArticle: { email: true, system: true }
        }
      }
    };
    
    const response = await axios.put(`${BASE_URL}/settings`, updateData, {
      ...testConfig,
      headers: {
        ...testConfig.headers,
        'Authorization': `Bearer ${authToken}`
      }
    });
    
    if (response.data.code === 200) {
      console.log('✅ 更新设置成功');
      console.log('📅 更新时间:', response.data.data.updatedAt);
      return true;
    } else {
      console.log('❌ 更新设置失败:', response.data.message);
      return false;
    }
  } catch (error) {
    console.log('❌ 更新设置请求失败:', error.message);
    if (error.response) {
      console.log('  状态码:', error.response.status);
      console.log('  错误信息:', error.response.data);
    }
    return false;
  }
}

// 测试无权限访问
async function testUnauthorizedAccess() {
  try {
    console.log('\n🚫 测试无权限访问...');
    
    // 不带token访问
    const response = await axios.get(`${BASE_URL}/settings`, testConfig);
    console.log('❌ 应该被拒绝但成功了');
    return false;
  } catch (error) {
    if (error.response && error.response.status === 401) {
      console.log('✅ 无权限访问被正确拒绝');
      return true;
    } else {
      console.log('❌ 无权限访问测试失败:', error.message);
      return false;
    }
  }
}

// 测试无效分类
async function testInvalidCategory() {
  try {
    console.log('\n🚫 测试无效分类...');
    
    const response = await axios.get(`${BASE_URL}/settings/invalid-category`, {
      ...testConfig,
      headers: {
        ...testConfig.headers,
        'Authorization': `Bearer ${authToken}`
      }
    });
    
    if (response.data.code === 400) {
      console.log('✅ 无效分类被正确拒绝');
      return true;
    } else {
      console.log('❌ 无效分类测试失败');
      return false;
    }
  } catch (error) {
    if (error.response && error.response.status === 400) {
      console.log('✅ 无效分类被正确拒绝');
      return true;
    } else {
      console.log('❌ 无效分类测试失败:', error.message);
      return false;
    }
  }
}

// 主测试函数
async function runTests() {
  console.log('🚀 开始测试Settings API接口...\n');
  
  // 1. 登录
  const loginSuccess = await login();
  if (!loginSuccess) {
    console.log('❌ 登录失败，无法继续测试');
    return;
  }
  
  // 2. 测试获取所有设置
  const allSettings = await testGetAllSettings();
  
  // 3. 测试获取各分类设置
  if (allSettings) {
    const categories = Object.keys(allSettings);
    for (const category of categories) {
      await testGetCategorySettings(category);
    }
  }
  
  // 4. 测试更新设置
  await testUpdateSettings();
  
  // 5. 测试无权限访问
  await testUnauthorizedAccess();
  
  // 6. 测试无效分类
  await testInvalidCategory();
  
  console.log('\n🎉 Settings API接口测试完成！');
}

// 运行测试
runTests().catch(error => {
  console.error('❌ 测试运行失败:', error.message);
});
